<template>
  <el-card>
    <template v-slot:header>
      <el-button type="primary" icon="el-icon-plus" @click="showAdd"
        >添加</el-button
      >
    </template>
    <template>
      <el-table
        border
        v-loading="loading"
        element-loading-text="玩命加载中，网络太垃圾了，赶紧换个宽带！！"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :data="trademarks"
        style="width: 100%"
        row-key="id"
      >
        <!-- 序号 -->
        <el-table-column type="index" align="center" label="序号" width="80">
        </el-table-column>

        <!-- 品牌名称 -->
        <el-table-column prop="tmName" label="品牌名称"> </el-table-column>

        <!-- 品牌LOGO -->
        <el-table-column label="品牌LOGO" prop="logoUrl">
          <template v-slot="{ row, $index }">
            <el-image
              :src="row.logoUrl"
              alt="logo"
              style="width: 100px; height: 80px"
            />
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              size="small"
              icon="el-icon-edit"
              @click="showUpdate(row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="remove(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: center; margin-top: 20px"
        :current-page="page"
        :page-sizes="[3, 6, 9]"
        :page-size="pageSize"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
      >
      </el-pagination>

      <!-- 对话框 -->
      <el-dialog
        :title="`${form.id ? '修改' : '添加'}品牌`"
        :visible.sync="dialogFormVisible"
      >
        <!-- 表单 -->
        <el-form
          ref="tmForm"
          :rules="rules"
          :model="form"
          label-width="20%"
          style="width: 80%"
        >
          <el-form-item label="品牌名称" prop="tmName">
            <el-input
              v-model="form.tmName"
              placeholder="请输入品牌名称"
            ></el-input>
          </el-form-item>

          <!-- 上传图片 -->
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              action="/dev-api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png文件，且不超过200kb
              </div>
            </el-upload>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addOrUpdate" :loading="saveLoading"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </template>
  </el-card>
</template>

<script>
export default {
  name: "TrademarkList",
  data() {
    return {
      trademarks: [], // 当前页列表
      page: 1, // 当前页码
      pageSize: 3, // 每页数量
      total: 0, // 总数量
      loading: false, //加载是否显示
      dialogFormVisible: false, //对话框是否显示
      //收集表单数据的form对象
      form: {
        logoUrl: "",
        tmName: ""
      },
      rules: {
        tmName: [
          //声明式校验
          { required: true, message: "请输入品牌名称", trigger: "change" },
          //自定义式校验
          { validator: this.validateTmName, trigger: "blur" }
        ],
        logoUrl: [{ required: true, message: "请上传LOGO", trigger: "change" }]
      },
      saveLoading: false // 是否显示保存的loading
    };
  },

  async mounted() {
    // 初始获取第一页列表显示
    this.pagingList();
  },

  watch: {
    dialogFormVisible(value) {
      //必须隐藏之前处理
      if (!value) {
        this.$refs.tmForm.clearValidate();
      }
    }
  },

  methods: {
    // 删除
    remove(trademark) {
      this.$confirm(`确认删除${trademark.tmName}吗?`, "提示", {
        type: "warning"
      })
        .then(async () => {
          //点击确定的回调
          //发送删除品牌的请求
          await this.$API.trademark.remove(trademark.id);
          this.$message.success("删除品牌成功！");
          //重新获取列表显示
          //如果当前页只剩一条数据了 显示上一页
          if (this.trademarks.length === 1) {
            this.page--;
          }
          this.pagingList();
        })
        .catch(error => {
          //点击取消的回调
          if (error === "cancel") {
            //点击取消才提示
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          }
        });
    },

    //添加或更新
    addOrUpdate() {
      //对所有表单进行验证
      this.$refs["tmForm"].validate(async valid => {
        //验证通过
        if (valid) {
          try {
            //添加/更新的请求
            const { form } = this;
            this.saveLoading = true; //请求前显示loading
            await this.$API.trademark[form.id ? "update" : "add"](form);
            //提示成功
            this.$message({
              type: "success",
              message: `${form.id ? "更新" : "添加"}成功`
            });
            // 关闭对话框
            this.dialogFormVisible = false;
            //重新获取分页列表
            if (!form.id) {
              this.page = 1;
            }
            this.pagingList();
          } finally {
            //异步请求成功/失败都会执行
            this.saveLoading = false; //请求完隐藏loading
          }
        }
      });
    },

    //对品牌名称进行校验
    validateTmName(rule, value, callback) {
      if (value.length < 2 || value.length > 10) {
         //校验不通过
        callback("长度在 2 到 10 个字符");
      } else {
        callback(); //校验通过
      }
    },

    //修改品牌
    showUpdate(trademark) {
      //指定表单数据
      this.form = { ...trademark };
      //显示对话框
      this.dialogFormVisible = true;
    },
    //添加品牌
    showAdd() {
      this.form = {
        logoUrl: "",
        tmName: ""
      };
      //显示对话框
      this.dialogFormVisible = true;
    },

    //图片上传
    handleAvatarSuccess(result) {
      //保存上传成功的图片url
      this.form.logoUrl = result.data;
      this.$refs.tmForm.clearValidate("logoUrl");
    },
    beforeAvatarUpload(file) {
      const isJPGOrPNG =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt200KB = file.size / 1024 <= 200;
      if (!isJPGOrPNG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt200KB) {
        this.$message.error("上传头像图片大小不能超过 200KB!");
      }
      return isJPGOrPNG && isLt200KB;
    },

    //分页器--获取数据
    handleSizeChange(pageSize) {
      //更新每页数量
      this.pageSize = pageSize;
      //更新当前页码
      this.page = 1;
      //获取当前页码的列表数据
      this.pagingList();
    },
    //处理页码发生改变的监听
    handleCurrentChange(currentPage) {
      //更新page
      this.page = currentPage;
      //获取当前页码的列表数据
      this.pagingList();
    },

    //请求数据
    async pagingList() {
      this.loading = true; //显示loading
      //请求获取数据
      const result = await this.$API.trademark.pagingList(
        this.page,
        this.pageSize
      );
      this.loading = false; //隐藏loading
      //读取数据更新
      const { records, total } = result.data;
      this.trademarks = records;
      this.total = total;
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
